import { Anchor, Avatar, Flex, Group } from "@mantine/core";
import { useAPIUtils } from "./APIUtilsProvider";

export default function UserPill({ user, userId }) {
  if (user) {
    return (
      <Flex>
        <Group
          gap={"xs"}
          style={(theme) => ({
            backgroundColor: theme.colors.gray[1],
            borderRadius: "16px",
          })}
        >
          <Avatar src={user.meta.avatar} alt={user.nickname} size={"sm"} />

          <Anchor href={`/users/${user.id}`} target="_blank" size="sm" pr={8}>
            {user.nickname}
          </Anchor>
        </Group>
      </Flex>
    );
  } else if (userId) {
    return <UserPillAsync userId={userId} />;
  } else {
    return <></>;
  }
}

function UserPillAsync({ userId }) {
  const { tanstackQuery } = useAPIUtils();
  const userQuery = tanstackQuery(`/api/admin/users/${userId}`);
  if (!userQuery.data) {
    return <></>;
  }

  const user = userQuery.data.user;

  return (
    <Flex>
      <Group
        gap={"xs"}
        style={(theme) => ({
          backgroundColor: theme.colors.gray[1],
          borderRadius: "16px",
        })}
      >
        <Avatar src={user.meta.avatar} alt={user.nickname} size={"sm"} />

        <Anchor href={`/users/${user.id}`} target="_blank" size="sm" pr={8}>
          {user.nickname}
        </Anchor>
      </Group>
    </Flex>
  );
}
